public class Test {
    private static int index = 0;
    public static TreeNode buildTreeHelper(int[] preorder,int[] inorder,int inLeft,int inRight) {
        if (inLeft >= inRight) {
            return null;
        }
        if (index >= preorder.length) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[index]);
        index++;
        int pos = findPos(inorder,inLeft,inRight,root.val);
        root.left = buildTreeHelper(preorder,inorder,inLeft,pos);
        root.right = buildTreeHelper(preorder,inorder,pos +1,inRight);
        return root;
    }

    public static int findPos(int[] inorder, int inLeft,int inRight,int val ){
        for(int i = inLeft;i < inRight;i++){
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;

    }


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        index = 0;
        TreeNode root = buildTreeHelper(preorder,inorder,0,inorder.length);
        return root;
    }
}


class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) {this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}
